from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional, List
from core.crawler import WebCrawler
from core.parser import HTMLParser
from core.ai_analyzer import LPRAnalyzer
from config.settings import LPR_LIST_URL

app = FastAPI(title="LPR API", description="获取LPR利率信息的API服务")

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class LPRResponse(BaseModel):
    success: bool
    message: str
    data: Optional[dict] = None

@app.get("/api/v1/lpr/latest", response_model=LPRResponse)
async def get_latest_lpr():
    """获取最新的LPR信息"""
    try:
        # 获取LPR列表页
        html_content = WebCrawler.fetch_webpage(LPR_LIST_URL)
        if not html_content:
            raise HTTPException(status_code=500, detail="无法获取LPR列表页面")
        
        # 解析列表页
        lpr_items = HTMLParser.parse_lpr_list(html_content)
        if not lpr_items:
            raise HTTPException(status_code=404, detail="未找到LPR信息")
        
        # 获取最新的LPR详情
        latest_lpr = lpr_items[0]
        detail_html = WebCrawler.fetch_webpage(latest_lpr['url'])
        if not detail_html:
            raise HTTPException(status_code=500, detail="无法获取LPR详情页面")
        
        # 解析详情页
        detail_content = HTMLParser.parse_lpr_detail(detail_html)
        if not detail_content:
            raise HTTPException(status_code=500, detail="无法解析LPR详情内容")
        
        # AI分析内容
        analyzer = LPRAnalyzer()
        lpr_info = analyzer.analyze_lpr_content(
            f"{detail_content['title']}\n{detail_content['content']}"
        )
        
        if not lpr_info:
            raise HTTPException(status_code=500, detail="AI分析LPR信息失败")
        
        return LPRResponse(
            success=True,
            message="获取成功",
            data={
                "title": detail_content['title'],
                "publish_date": lpr_info['publish_date'],
                "one_year_lpr": lpr_info['one_year_lpr'],
                "five_year_lpr": lpr_info['five_year_lpr']
            }
        )
        
    except Exception as e:
        return LPRResponse(
            success=False,
            message=f"获取LPR信息失败: {str(e)}",
            data=None
        ) 